<?php

namespace app\admin\controller\sport;

use app\common\controller\Backend;
use app\common\library\Batch;
use app\admin\model\sport\Score as ScoreModel;
use app\admin\model\sport\Area as AreaModel;

/**
 * 地区列管理
 *
 * @icon fa fa-circle-o
 */
class Area extends Backend
{

    /**
     * Area模型对象
     * @var \app\admin\model\sport\Area
     */
    protected $model = null;

    protected $_sportTypeNum = 4;

    private $_templateDir = '/uploads/template';

    protected $scoreTypes = [
        'middle'  => '中考体育',
        'senior'  => '高考体育',
    ];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\sport\Area;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $items = $list->items();
        foreach ($items as &$item) {
            if (!empty($item->middle_template)) {
                $item->middle_template = cdnurl($item->middle_template, true);
            }
            if (!empty($item->senior_template)) {
                $item->senior_template = cdnurl($item->senior_template, true);
            }
        }
        $result = ['total' => $list->total(), 'rows' => $items];
        return json($result);
    }


    public function createTemplate()
    {
        $areaId = input('get.area_id');    
        $type = input('get.type');
        if (empty($areaId) || empty($type)) {
            $this->error('缺少参数');
        }
        $area = AreaModel::find($areaId);
        // 查找是否满足生成模版的标准
        $scores = ScoreModel::where('sport_area_id', $areaId)->where('score_type', $type)->where('status', 'normal')->select();
        if ($type == 'middle') {
            $sportTypes = [];
            foreach ($scores as $s) {
                if (!in_array($s->sport_type_id, $sportTypes)) {
                    $sportTypes[] = $s->sport_type_id;
                }
            }
            if (count($sportTypes) != $this->_sportTypeNum) {
                $this->error('中考体育项目的4个类别还未设置全');
            }
        } else if ($type == 'senior') {
            $sportMaleScores = [];
            $sportFeMaleScores = [];
            foreach ($scores as $s) {
                if ($s->sex == 1 && !in_array($s->project_name, $sportMaleScores)) {
                    $sportMaleScores[] = $s->project_name;
                } else if ($s->sex == 2 && !in_array($s->project_name, $sportFeMaleScores)) {
                    $sportFeMaleScores[] = $s->project_name;
                }
            }
            if (count($sportMaleScores) != $this->_sportTypeNum) {
                $this->error('高考体育项目中男生未设置满'.$this->_sportTypeNum.'项');
            }
            if (count($sportFeMaleScores) != $this->_sportTypeNum) {
                $this->error('高考体育项目中女生未设置满'.$this->_sportTypeNum.'项');
            }
            // 需要判断男女项目是否名称一样
            $diff = array_diff($sportMaleScores, $sportFeMaleScores);
            if(!empty($diff)) {
                $this->error('高考体育项目中男女项目名称需保持一致');
            }
        }
        $curPath = dirname(dirname(APP_PATH));
        $outDestDir = $curPath . $this->_templateDir;
        $this->createDir($outDestDir);
        $file = $area->area_name .'_'.$this->scoreTypes[$type].'_导入模版.xlsx';
        $saveFilename = $this->_templateDir . '/' . $file;
        $filename = $outDestDir . '/' . $file;
        $batchLib = new Batch();
        $res = $batchLib->createTemplate($areaId, $type, $filename);
        if ($res === true) {
            if ($type == 'middle') {
                $area->middle_template = $saveFilename;
            } else {
                $area->senior_template = $saveFilename;
            }
            $area->save();
        }

        $this->success('模版生成完毕');
    }


    private function createDir($destDir)
    {   
        if (!is_dir($destDir)) {
            @mkdir($destDir, 0755, true);
        }   
    }
}
